package com.jtpay.payresulthelper.ui.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.jtpay.payresulthelper.BuildConfig;
import com.jtpay.payresulthelper.R;
import com.jtpay.payresulthelper.http.ApiHelper;
import com.jtpay.payresulthelper.service.AliAccessibilityService;
import com.jtpay.payresulthelper.service.AliNotificationCollectorService;
import com.jtpay.payresulthelper.util.ActivityHelper;
import com.jtpay.payresulthelper.util.LogUtil;
import com.jtpay.payresulthelper.util.PayContext;
import com.jtpay.payresulthelper.util.SharedPreferenceUtil;

import static com.jtpay.payresulthelper.constant.HooKConstant.ACTION_START_DOT;
import static com.jtpay.payresulthelper.util.ActivityHelper.*;
import static com.jtpay.payresulthelper.util.PayContext.*;

/**
 * Description:
 * File: BaseActivity.java
 * Author: Administrator
 * Create: 2018/08/14 10:03
 */
public abstract class BaseActivity extends AppCompatActivity {
    protected SharedPreferenceUtil sharedPreferenceUtil = new SharedPreferenceUtil();
    protected OrderReceiver mOrderReceiver = new OrderReceiver();
    protected Handler mHandler = new Handler();
    protected ApiHelper apiHelper;
    protected Gson gson = new Gson();
    protected Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setLayoutId());
        keepScreenLongLight();
        String versionName = Debug ? "(ce)" : "";
        setTitle(getString(R.string.product_program) + versionName);
        android.support.v7.app.ActionBar actionBar = this.getSupportActionBar();
        if (actionBar != null) {
            actionBar.setSubtitle(String.format("%s%s",
                    getString(R.string.version), BuildConfig.VERSION_NAME));
        }
        initView();
        initData();
        mContext = this;
    }

    protected abstract void initView();

    protected abstract void initData();

    protected abstract int setLayoutId();

    protected ApiHelper getApiHelper() {
        if (apiHelper == null) {
            apiHelper = ApiHelper.getInstance(this);
        }
        return apiHelper;
    }

    protected void openAccessibilityServiceSettingIfNeed(boolean isShow) {
        if (!isAccessibilitySettingsOn(this)) {
            LogUtil.log("Opening ProductService!");
            ActivityHelper.openAliService();
            //查询是否服务开启成功
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isAccessibilitySettingsOn(mContext)) {
                        showLog(getString(R.string.service_auto_open_success_tips));
                    } else {
                        showLog(getString(R.string.service_auto_open_fail_tips));
                    }
                }
            }, 500);
        } else if (isShow) {
            showLog(getString(R.string.service_auto_open_success_tips));
        }
    }

    protected void startNotifyListener() {
        if (!isNotifyListenerSettingOn()) {
            openNotificationListener();
        } else {
            restartNotificationListener();
        }
//        openNotificationListener();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isNotifyListenerSettingOn()) {
                    showLog(getString(R.string.notify_listener_open_success_tips));
                } else {
                    showLog(getString(R.string.notify_listener_open_fail_tips));
                }
            }
        }, 500);
    }

    /**
     * isAccessibilitySettingsOn check service is opened
     *
     * @param context Context
     * @return check result
     */
    protected boolean isAccessibilitySettingsOn(Context context) {
        int accessibilityEnabled = 0;
        final String service = getPackageName() + "/" + AliAccessibilityService.class.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            showLog("Error ，productService to not found: " + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        if (accessibilityEnabled == 1) {
            LogUtil.log("***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(context.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        LogUtil.log("***ACCESSIBILITY IS OPENED***");
                        return true;
                    }
                }
            } else {
                LogUtil.log("***ACCESSIBILITY IS CLOSED***");
            }
        }

        return false;
    }

    /**
     * isNotifyListenerSettingOn
     *
     * @return result
     */
    protected boolean isNotifyListenerSettingOn() {
        String string = Settings.Secure.getString(getContentResolver(),
                "enabled_notification_listeners");
        if (TextUtils.isEmpty(string)) {
            return false;
        } else {
            return string.contains(AliNotificationCollectorService.class.getName());
        }
    }

    protected void setViewVisibility(final View view, final int visibility) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                view.setVisibility(visibility);
            }
        });
    }


    protected void startAlarmSettingUI() {
        /*Intent alarmIntent = new Intent(AlarmClock.ACTION_SET_ALARM);
        startActivity(alarmIntent);*/
        startAlarmActivity();
    }

    /**
     * doRequestPermissions
     */
    protected void doRequestPermissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                    ) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.READ_PHONE_STATE
                        }, 0);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        checkRequestPermissions();
    }

    /**
     * checkRequestPermissions result
     */
    protected void checkRequestPermissions() {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED
                || ActivityCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED
                || ActivityCompat.checkSelfPermission(this,
                Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED
                ) {
            showToast(getString(R.string.permission_denied_error));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 500);
        }
    }

    protected void setFocusable(View view, boolean clickable) {
        view.setFocusable(clickable);
        view.setFocusableInTouchMode(clickable);
        if (clickable) {
            view.requestFocus();
        }
    }

    /**
     * 屏幕常亮
     */
    protected void keepScreenLongLight() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    protected void openNotifySettingUI() {
        startActivity(new Intent(
                "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
    }

    protected void openAccessibilityServiceSetting() {
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    protected void openProgramSetting() {
        Intent intent = new Intent()
                .setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                .setData(Uri.fromParts("package", getPackageName(), null));
        startActivity(intent);
    }

    protected abstract void showLog(String content);

    protected abstract void showToast(String content);

    protected abstract void verifyResult(boolean result);

    protected abstract void uploadPayResult();

    protected abstract void pulseSpeed();

    protected abstract void stopPulseSpeed();

    protected void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter(ACTION_VERIFY_RESULT);
        intentFilter.addAction(ACTION_UPLOAD_PAY_RESULT);
        intentFilter.addAction(ACTION_SHOW_LOG);
        intentFilter.addAction(ACTION_START_DOT);
        intentFilter.addAction(ACTION_ALI_OFFLINE);
        registerReceiver(mOrderReceiver, intentFilter);
    }

    protected void unRegisterReceiver() {
        unregisterReceiver(mOrderReceiver);
    }

    //处理订单结果
    class OrderReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            LogUtil.log("BaseActivity onReceive  " + action);
            switch (action) {
                case ACTION_VERIFY_RESULT:
                    showLog("账号验证结果： " + PayContext.VerifyAccountResult);
                    verifyResult(PayContext.VerifyAccountResult);
                    break;
                case ACTION_UPLOAD_PAY_RESULT:
                    uploadPayResult();
                    break;
                case ACTION_SHOW_LOG:
                    showLog(intent.getStringExtra(SHOW_LOG_CONTENT));
                    break;
                case ACTION_START_DOT:
                    pulseSpeed();
                    break;
                case ACTION_ALI_OFFLINE:
                    if (getApiHelper().getAuthorize()) {
                        showLog(getString(R.string.ali_offline_notify_msg));
                    }
                    stopPulseSpeed();
                    break;
                default:
                    break;
            }
        }
    }
}
